package OnlineLibrary.managers;

import java.util.ArrayList;

import org.omg.CosNaming.NameComponent;
import BookStore.managers.AuctionMgr_Iface.AuctionMgrHelper;
import Common.Customer;
import Util.CSVBookParser;
import Util.Util;

/**
 * Manager aiming to manage the catalog of each book store
 * 
 */
public class AuctionMgr extends Mgr {

	private BookStore.managers.AuctionMgr_Iface.AuctionMgr[] BS;

	public AuctionMgr() {
		super();
		// retrieve each book store servant
		BS = new BookStore.managers.AuctionMgr_Iface.AuctionMgr[ids.length];

		// call all auction servants

		for (int i = 0; i < this.ids.length; i++) {
			String id = this.ids[i];
			NameComponent[] name = new NameComponent[] { new NameComponent(
					"Auction", "Object" + id) };
			try {
				BS[i] = AuctionMgrHelper.narrow(context.resolve(name));
			} catch (Exception e) {
				System.out.println("null");
				BS[i] = null;
			}
		}
	}

	/**
	 * Launch an asynchronous auction. The online library chooses a book store
	 * to manage the auction
	 * 
	 * @param isbn
	 *            book's isbn to sell
	 * @param price
	 *            starting price of this book
	 * @param client
	 *            book's customer
	 * @return true if the auction is started, otherwise false
	 */
	public boolean launchAsynchronousAuction(String isbn, float price,
			Customer client) {
		if (ids == null || ids.length == 0)
			return false;

		boolean found = false;
		int i = 0;
		int sellNumber = getCurrentSellNumber() + 1;
		String entry = sellNumber + ";" + isbn + ";" + "unknown" + ";"
				+ client.firstname + ";" + client.lastname;
		// register temporally the book sell by waiting for the future sell
		// price
		this.registerSellBook(entry);
		logger.info("Has registered a temporary book sell by waiting for the bookstore's price..."+sellNumber);

		while (!found && i < BS.length) {
			ArrayList<String> iors = getIORList();
			iors.remove(i);
			try {
				BS[i].initLaunch(isbn, price, iors.toArray(new String[iors.size()]), sellNumber);
				found = true;
			} catch (Exception e) {
				logger.info("BookStore nr." + i + " is absent");
			}
			i++;
		}

		return found;
	}

	private int getCurrentSellNumber() {
		CSVBookParser parser = new CSVBookParser();
		String save = Util.getPropertiesAttribute(super.prop, "csv");
		return parser.getNumberOfLines(save);
	}


	public boolean registerSellBook(String buy) {
		String save = Util.getPropertiesAttribute(super.prop, "csv");
		if (save == null)
			logger.info("[ERROR] file " + super.prop + " is absent");
		return CSVBookParser.writeFile(buy, save);
	}


	private ArrayList<String> getIORList() {
		ArrayList<String> res = new ArrayList<String>();
		if (BS == null)
			return res;
		for (BookStore.managers.AuctionMgr_Iface.AuctionMgr mgr : BS)
			res.add(orb.object_to_string(mgr));
		return res;
	}

}
